cc.Class({
    extends: cc.Component,

    properties: {
        motor: cc.Prefab,
        blocks: require('Blocks'),
        selects: [cc.Node],
    },

    onLoad () {
        this.startX = this.node.x;
        this.node.find('finishline').x = GLOBAL.TOTAL_MOVE * GLOBAL.FACTOR_MOVE;
        this.node.find('line_100').x = GLOBAL.TOTAL_MOVE * GLOBAL.FACTOR_MOVE * 7 / 8;
        this.node.find('line_200').x = GLOBAL.TOTAL_MOVE * GLOBAL.FACTOR_MOVE * 6 / 8;
        this.node.find('line_300').x = GLOBAL.TOTAL_MOVE * GLOBAL.FACTOR_MOVE * 5 / 8;
        for(var i in this.selects) this.selects[i].active = false;

        this.emojiOrder = 0;
        this.emojiArray = [0, 1, 2, 3, 4];
    },

    loadMotors() {
        this.motors = [];
        var roles = ['红', '绿', '蓝', '紫', '黄'];
        for(var i = 0; i < 5; i++) {
            var obj = cc.instantiate(this.motor);
            obj.parent = this.node;
            obj.y = 112 - i * 66;
            obj.on('EMOJI_END', this.onEmojiEnd, this);
            obj.on('MOVE_CAPTURE', this.onMoveCapture, this);
            obj.getComponent(dragonBones.ArmatureDisplay).armatureName = roles[i];
            this.motors.push(obj.getComponent('Motor'));
        }
    },

    onMoveReady() {
        this.node.x = this.startX;
        this.blocks.node.removeAllChildren();
        for(var i in this.motors) {
            this.motors[i].readyMove();
            this.selects[i].active = false;
        }
    },

    onMoveStart(data, timer) {
        for(var i in data) {
            var d = data[i];
            var motor = this.motors[d.bikeId - 1];
            var road = JSON.parse(d.track);
            motor.startMove(road, timer / GLOBAL.FACTOR_TIME);
            this.blocks.setRoadBlock(road, motor.node.y);
        }
        this.emojiOrder = 0;
        this.shuffleEmoji();
        this.onEmojiEnd();
    },

    onMoveCapture(evt) {
        if(evt.detail.moveData.place == 1) this.node.emit('MOVE_CAPTURE');
    },

    onMoveSprint() {
        for(var i in this.motors) this.motors[i].sprintMove();
    },

    shuffleEmoji() {
        for(var i = 0; i < 5; i++) {
            var rdm = Math.rand(i, 4);
            var temp = this.emojiArray[i];
            this.emojiArray[i] = this.emojiArray[rdm];
            this.emojiArray[rdm] = temp;
        }
    },

    onEmojiEnd() {
        this.emojiOrder++;
        this.emojiOrder > 4 && (this.emojiOrder = 0);
        this.motors[this.emojiArray[this.emojiOrder]].playEmoji()
    },

    showSelect(id) {
        this.selects[id].active = true;
    },

    updateSelect(id, x) {
        this.selects[id].x = x;
    },

    updateX(x) {
        this.node.x = this.startX - x;
    },
});
